import QtQuick 2.0
import QtQuick.Controls 2.12

Rectangle {
    id:switchBackground
    implicitWidth: 60
    implicitHeight: 30
    antialiasing: true

    property bool checked: false
    property real switchInterval: 2.5
    property color onColor: "#50b050"
    property color offColor: "gray"
    property real handleDia: height - (switchInterval * 2)

    signal sSwitchChanged()

    radius: width / 2
    color: "gray"
    border.color: "dimgrey"
    border.width: switchInterval
    Rectangle {
        id:switchHandle
        x:switchInterval
        y:switchInterval
        implicitWidth: handleDia
        implicitHeight: handleDia
        antialiasing: true
        radius: handleDia
        color: "cornsilk"
        visible: true
    }

    PropertyAnimation {
        id:animHandle
        target: switchHandle
        property: "x"
        from:switchHandle.x
        duration: 100
    }

    ColorAnimation {
        id:backgroundColorAnim
        target: switchBackground
        property: "color"
        duration: 100
    }

    MouseArea {
        anchors.fill:parent
        acceptedButtons: Qt.LeftButton
        onClicked: {
            if(animHandle.running) return
            checked = !checked
            emit: sSwitchChanged()
        }
    }
    onCheckedChanged: {
        if(checked == true)
        {
            backgroundColorAnim.from = offColor
            backgroundColorAnim.to = onColor
            backgroundColorAnim.start()
            animHandle.to = switchBackground.x + switchInterval + (switchBackground.width - switchInterval * 2 - handleDia)
            animHandle.start()
        }
        else
        {
            backgroundColorAnim.from = onColor
            backgroundColorAnim.to = offColor
            backgroundColorAnim.start()
            animHandle.to = switchBackground.x + switchInterval
            animHandle.start()
        }
    }
}
